package com.eagle.support.common;

import android.os.Handler;

import com.kinstalk.voip.sdk.api.WeaverService;
import com.kinstalk.voip.sdk.interfaces.WeaverUserSipStatusListener;
import com.kinstalk.voip.sdk.logic.user.UserConstants;
import com.kinstalk.voip.sdk.logic.user.UserLogic;

/**
 * Created by gc on 2017/1/5.
 */

public class AccountStatusManager implements WeaverUserSipStatusListener {

    private static AccountStatusManager gInstance;
    private static EventHandler mEventHandler;

    private String uid, password, appKey, appSecret, appSource;
    private boolean isUserCallLogin = false;

    public static AccountStatusManager getInstance() {
        if (gInstance == null) {
            gInstance = new AccountStatusManager();
        }
        return gInstance;
    }

    private AccountStatusManager() {
        isUserCallLogin = false;
    }

    public static void setEventHandler(EventHandler eventHandler) {
        mEventHandler = eventHandler;
    }

    public void login(String uid, String password, String appKey, String appSecret, String appSource) {
        this.uid = uid;
        this.password = password;
        this.appKey = appKey;
        this.appSecret = appSecret;
        this.appSource = appSource;
        isUserCallLogin = true;
        WeaverService.getInstance().dispatchRequest(new UserLogic.UserLogin(uid, password, appKey, appSecret, appSource, null));
    }

    public void logout() {
        isUserCallLogin = false;
        WeaverService.getInstance().dispatchRequest(new UserLogic.UserLogout(null));
    }

    @Override
    public void onStatusChange(int status) {
        if (mEventHandler == null) {
            return;
        }

        Handler handler = mEventHandler.getHandler();
        handler.sendMessage(handler.obtainMessage(EventHandler.KEY_LOGIN_RESULT, status, 0));
        if (status == UserConstants.UserStatus.OFFLINE) {
            if (isUserCallLogin) {
                WeaverService.getInstance().dispatchRequest(new UserLogic.UserLogin(uid, password, appKey, appSecret, appSource, null));
            }
        }
    }

    public boolean isLogged() {
        return isUserCallLogin;
    }
}
